import axios from "axios";
import { Toast } from "antd-mobile";

import { getStorageToken } from "@/utils/auth";
import { backendBaseUrl } from "./constant";

// create an axios instance
const service = axios.create({
  baseURL: backendBaseUrl, // url = base url +  url
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    // let token = state.user.token;
    if (getStorageToken()) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["authorization"] = getStorageToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 2000) {
      Toast.show({
        content: res.message,
      });
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log(error); // for debug
    // token过期 跳转到登录页
    if (error.response.data.code === -2) {
      location.hash = "/login";
    }
    Toast.show({
      content: error.response.data.message || "error",
    });
    return Promise.reject(error);
  }
);

export default service;
